<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\9\25 0025
 * Time: 9:52
 */

namespace app\Lib\Model\SysConfig\SysConfigManage;


use app\Lib\Exception\BlException;
use app\Lib\InterfaceIn\User\UserHandle;
use app\Lib\Model\DbModel\AdminConfig;

class AddConfig extends ConfigCommon implements \app\Lib\InterfaceIn\SysConfig\SysConfigManage\AddConfig
{
    /** @var UserHandle $opUser */
    private $opUser;
    /**
     * 初始化
     * AddConfig constructor.
     * @param UserHandle $opUser
     */
    public function __construct(UserHandle $opUser)
    {
        $this->opUser = $opUser;
    }

    /**
     * 执行操作
     * @return bool
     * @throws BlException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function run()
    {
        $model                      = $this->getTable();
        $data                       = $this->handleArray();
        $validate                   = $this->getValidate();
        $data[$model->_create_uid]  = $this->opUser->getUid();
        $data[$model->_create_time] = time();
        $this->validate($data);
        if(!($validate->scene('add')->check($data))){
            throw new BlException($validate->getError());
        }
        $result                     = $model->insert($data);
        if(!$result){
            throw new BlException('新增失败');
        }
        return true;
    }

    /**
     * 参数验证
     * @param $data
     * @return bool
     * @throws BlException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function validate($data){
        $model= $this->getTable();
        $info = $model->where($model->_status,1)->where(function ($query)use($data){
            $models =$this->getTable();
            /**@var AdminConfig $query  */
            $query->whereOr($models->_title,$data[$models->_title])->whereOr($models->_variable,$data[$models->_variable]);
        })->field([$model->_title,$model->_variable])->find();
        if($info && $info[$model->_title] == $data[$model->_title]){
            throw new BlException('配置标题已存在');
        }
        if($info && $info[$model->_variable] == $data[$model->_variable]){
            throw new BlException('配置key已存在');
        }
        return true;
    }

}